import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpClient {
    Socket socket = null;
    public TcpClient(String serverIP,int port) throws IOException {
        socket = new Socket(serverIP,port);
    }

    public void start() {
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerFromSocket = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                // 1 - 从硬盘上读取用户输入的内容
                System.out.print("->");
                String request = scanner.next();

                // 2 - 把读取的内容构造成请求发送给服务器
                printWriter.println(request); // 发送是带有换行的
                printWriter.flush(); // 手动刷新缓冲区 , 将缓冲区的数据发送到网卡
                // 3 -- 从服务器读取响应
                String response = scannerFromSocket.next();

                // 4 -- 将响应显示到控制台
                System.out.printf("[req %s resp %s]\n",request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        // 传服务器的ip和端口
        TcpClient tcpClient = new TcpClient("127.0.0.1",9090);
        tcpClient.start();
    }

}
